package com.person.jc.service.test.inspect;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.person.jc.common.Constants;
import com.person.jc.common.SQLSpell;
import com.person.jc.entity.TsUser;
import com.person.jc.service.Service;
import com.person.jc.service.base.device.BdDevicePartsService;
import com.person.jc.utils.DateUtils;
import com.person.jc.utils.SessionKit;
import com.person.jc.utils.Utils;

public class BsReconditionLogService extends Service {
	
	public static BsReconditionLogService me = new BsReconditionLogService();
	private static String optMenu = "我的检修任务";
	
	public List<Record> getViewList(Map<String, Object> map) {
		String temp = "";
		List<Object> params = new ArrayList<Object>();
						
		String tempSql = "SELECT DISTINCT\n" +
						"	 oe.*,rl.check_user check_user_id,  ("+SQLSpell.userName("rl.check_user")+") check_user,\n rl.opt_user inspect_user_id,  ("+SQLSpell.userName("rl.opt_user")+") inspect_user, brcl.confirm_status,\n " +
						"	 ("+SQLSpell.kindName("volume_category", "oe.volume_category")+") volume_category_,\n" +
						"	DATE_FORMAT(rl.opt_date, '%Y-%m-%d') inspect_date, rl.check_remark, rl.repair_remark, rl.address, rd.*,rcl.rec_id,rcl.remark rcl_remark,rcl.address rcl_address,rcl.original_record,rcl.original_record_ok,rcl.scopes,DATE_FORMAT(rcl.opt_date, '%Y-%m-%d') complate_date,rl.equ_id,\n" +
						"	 ("+SQLSpell.kindName("device_type", "oe.device_type")+") device_type_,\n" +
						"	 (SELECT group_concat(t.device_name) from bd_device_info t where FIND_IN_SET(t.device_id, oe.gas_type)) gas_type_,\n" +
						"	 ("+SQLSpell.kindName("yes_or_no", "oe.if_cert")+") if_cert_\n" +
						"FROM\n" +
						"	  bs_task_assign a\n" +
						"        LEFT JOIN\n" +
						"    bs_task_assign_user au ON a.assign_id = au.assign_id\n" +
						"        LEFT JOIN\n" +
						"    bs_order_equipment oe ON au.order_id = oe.order_id AND au.device_type = oe.device_type\n" +
						"        LEFT JOIN\n" +
						"    bs_order o ON oe.order_id = o.order_id\n" +
						"        LEFT JOIN\n" +
						"		bs_repair_reg_log rl ON oe.equ_id = rl.equ_id\n" +
						"        LEFT JOIN\n" +
						"    (select d.log_id, group_concat(distinct f.fault_name order by f.fault_name asc separator '; ') fault_name,group_concat(DISTINCT concat(p.parts_name, '[' , p.parts_code, ']') ORDER BY p.parts_name ASC, p.parts_code ASC separator '; ') parts_name from bs_repair_check_detail d left join bd_fault_info f on d.fault_id = f.fault_id left join bd_device_parts p on d.parts_id = p.parts_id group by d.log_id) rd on rd.log_id = rl.log_id\n" +
						"			 LEFT JOIN\n" +
						"		bs_recondition_log rcl on rl.log_id = rcl.log_id\n " +
						"	inner join bs_repair_confirm_log brcl on rl.log_id = brcl.log_id  and brcl.confirm_status=1  \n " +
						"WHERE a.order_type = 3\n";
		StringBuffer sql = new StringBuffer(tempSql);
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("userId")))){
			sql.append("   AND au.user_id = ?\n");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("orderId")))){
			sql.append("AND o.order_id = ?\n");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("custId")))){
			sql.append("AND o.cust_id = ?\n");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("deviceType")))){
			sql.append("AND oe.device_type = ?\n");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("equId")))){
			sql.append("AND oe.equ_id = ?\n");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("deviceNo")))){
			sql.append("AND oe.device_no like ?\n");
			params.add("%" + temp + "%");
		}
		sql.append("ORDER BY o.cust_id, oe.order_id");
		return Db.find(sql.toString(), Utils.getObjParam(params));
	}

	public List<Record> getFaultPartsListBy(String equId) {
		String sql = "SELECT f.fault_id, f.fault_name, group_concat(DISTINCT concat(p.parts_name, '[', p.parts_code, ']') ORDER BY p.parts_name ASC, p.parts_code ASC separator ', ') parts_name\n" +
				"  FROM bs_repair_reg_log t\n" +
				"  left join bs_repair_check_detail d\n" +
				"    on t.log_id = d.log_id\n" +
				"left join bd_fault_info f on d.fault_id = f.fault_id\n" +
				"left join bd_device_parts p on d.parts_id = p.parts_id\n" +
				" where t.equ_id = ?\n" +
				"GROUP BY f.fault_id";
		return Db.query(sql, equId);
	}

	public void save(Map<String, Object> map) {
		Record record = new Record();
		record.set("log_id", map.get("logId"));
		record.set("order_id", map.get("orderId"));
		record.set("cust_id", map.get("custId"));
		record.set("equ_id", map.get("equId"));
		record.set("device_type", map.get("deviceType"));
		record.set("repair_user", map.get("optUser"));
		if( map.get("ifCer")!=null &&  map.get("ifCert").toString().equals(""))
		record.set("if_cert", map.get("ifCert"));
		record.set("opt_user", map.get("optUser"));
		record.set("opt_date", DateUtils.getDateTime());
		record.set("remark", map.get("remark"));
		record.set("address", map.get("address"));
		record.set("original_record",map.get("originalRecord"));
		record.set("scopes",map.get("scopes"));


		if(map.get("recId")!=null && !map.get("recId").equals("")){
			record.set("rec_id",map.get("recId"));
			Db.update("bs_recondition_log","rec_id", record);

		}else{
			Db.save("bs_recondition_log", record);

		}
		
		String idxSql = "SELECT LAST_INSERT_ID() from dual ";
		BigInteger recId = Db.queryColumn(idxSql);
		super.setCRUD(optMenu, "C", "新增检修记录：" + recId);
	}
	
	
	/*
	 * 查询订单未检查数量
	 */
	public Integer getUnInspectsNum(String orderId) {
		String sql = "select count(0) from bs_order_equipment oe\n" +
				"left join bs_repair_reg_log rl on oe.equ_id = rl.equ_id\n" +
				"left join bs_repair_confirm_log rcl on rl.log_id = rcl.log_id\n" +
				"left join bs_parts_confirm_log pcl on rl.log_id = pcl.log_id\n" +
				"left join bs_recondition_log rl1 on oe.equ_id = rl1.equ_id\n" +
				"where oe.order_id = ?\n" +
				"and rcl.confirm_status = 1 \n" +
				"and pcl.confirm_status = 1\n" +
				"and rl1.rec_id is null";
		Long num = Db.queryLong(sql, orderId);
		return num.intValue();
	}

	/*
	 * 验证维修配件是否已出库
	 */
	public void partsOut(String logId) {
		String sql = "select t.parts_id,\n" +
					"       (select c.cust_name from bd_customer c where c.cust_id = rl.cust_id) cust_name,\n" + 
					"       (select oe.device_no from bs_order_equipment oe where oe.equ_id = rl.equ_id) device_no\n" + 
					"  from bd_device_parts t\n" + 
					"  left join bs_repair_check_detail rd on t.parts_id = rd.parts_id\n" + 
					"  left join bs_repair_reg_log rl on rl.log_id = rd.log_id\n" + 
					" where t.parts_status in (0, 1) and rd.log_id = ?";
		
		List<Record> list = Db.find(sql, logId);
		if(list!=null && list.size()>0){
			TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
			for (Record record : list) {
				Record outRecord = new Record();
				outRecord.set("parts_id_", record.get("parts_id"));
				outRecord.set("use_time", DateUtils.getDateTime());
				outRecord.set("use_by", tsUser.getUserId());
				outRecord.set("use_to", record.get("cust_name")+"-"+record.get("device_no"));
				Db.save("bd_device_parts_outlog", outRecord);
				BdDevicePartsService.me.update(new String[]{record.get("parts_id").toString()}, 2);
				super.setCRUD("设备出库", "C", "新增出库记录，设备编号：" + record.get("parts_id"));
			}
		}
	}

}
